package com.fearless.test02;

/*

    生产者消费者问题。不使用JUC的版本

 */



//共享数据类。应该只含有属性和方法
public class Data {

    private int count=0;//共享变量


   synchronized void consume()  {
        this.notifyAll();
        if(count > 0){
            System.out.println("现在库存是"+count+Thread.currentThread().getName()+"开始消费");
            count--;
        }else {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


   synchronized void produce()  {
        this.notifyAll();
            if(count==0){
                System.out.println("现在库存是"+count+Thread.currentThread().getName()+"开始生产");
                count++;
            }else {
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

    }


}



class Test{
    public static void main(String[] args) {

        Data data=new Data();

        new Thread(()->{
            for (int i = 0; i <50 ; i++) {
                data.produce();
            }
        },"生产者").start();


        new Thread(()->{
            for (int i = 0; i <50 ; i++) {
                data.consume();
            }
        },"消费者").start();

    }
}